package com.buka.user.dao;

import com.buka.user.entity.User;
import com.buka.utils.JDBCUtil;

import java.sql.*;
import java.util.List;

public class UserDao {

    public int save(User user){
        String sql = "insert into user (id,userName,passwd,age,sex,email,phoneNo,areaid,hobby,`desc`) value (?,?,?,?,?,?,?,?,?,?)";
        return JDBCUtil.excuteUpdate(sql, user, User.class);
    }


   public int update(User user){
        String sql = "update user set userName=?,passwd=?," +
                "age=?,sex=?,email=?,phoneNo=?," +
                "areaid=?,hobby=?,`desc`=? " +
                "where id=?";

        return JDBCUtil.executeUpdateByArr(sql,user.getUserName(),user.getPasswd(),user.getAge(),
                user.getSex(),user.getEmail(),user.getPhoneNo(),user.getAreaId(),user.getHobby(),user.getDesc(),
                user.getId());

   }


    public List<User> selectList(){
        String sql= "select * from user";
        return JDBCUtil.executeQuery(sql,User.class);
    }


    public static void main(String[] args) throws Exception{
        Class.forName("com.mysql.cj.jdbc.Driver");
        //建立连接
        String url = "jdbc:mysql://localhost:3306/java-web-2411";
        String userName = "root";
        String passwd = "123456";
        Connection connection = DriverManager.getConnection(url, userName, passwd);
        System.out.println();
    }

    public User selectByNameAndPasswd(String userName, String passwd) {
        String sql = "select * from user where userName = ? and passwd = ? ";
        List<User> userList = JDBCUtil.executeQuery(sql, User.class, userName, passwd);
        if(userList.isEmpty()){
            return null;
        }else{
            return userList.get(0);
        }
    }

    public User selectById(String id) {
        String sql = "select * from user where id = ?";
        List<User> objects = JDBCUtil.executeQuery(sql, User.class, id);
        if(objects.isEmpty()){
            return null;
        }else{
            return objects.get(0);
        }
    }

    public int deleteById(String id) {
        String sql = "delete from user where id = ?";
        return JDBCUtil.executeUpdateByArr(sql, id);
    }
}
